package com.dyz.wsw.security.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.Objects;

/**
 * @author dyz
 * @date 2025/2/9 16:11
 */
@Configuration
@Slf4j
public class RedisConfig {

    private final RedisTemplate<String, String> redisTemplate;

    public RedisConfig(RedisTemplate<String, String> redisTemplate) {
        log.info("创建配置类对象: RedisConfig");
        this.redisTemplate = redisTemplate;
    }

    @Bean
    @ConditionalOnMissingBean
    public ReactiveRedisTemplate<String, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
        RedisSerializationContext.RedisSerializationContextBuilder<String, Object> builder = RedisSerializationContext.newSerializationContext();

        //配置序列化器
        builder.key(RedisSerializer.string());
        builder.value(RedisSerializer.json());
        builder.hashKey(RedisSerializer.string());
        builder.hashValue(RedisSerializer.json());

        return new ReactiveRedisTemplate<>(factory, builder.build());
    }

    @PostConstruct
    public void init(){
        try {
            Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection().ping();
        }catch (Exception e){
            log.error("无法连接到Redis,请确认redis的启动");
            throw new ApplicationContextException(e.getMessage());
        }
    }

}
